package br.com.obardavez.base.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Id;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.obardavez.base.dao.BaseDAO;
import br.com.obardavez.base.entity.BaseEntity;

public class BaseDAOImpl<T extends BaseEntity> extends DAOImpl implements BaseDAO<T>  {

	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	public T findById(Serializable id) {
		T entity = null;

		if (id != null) {

			try {
			
				StringBuilder search = new StringBuilder(200);
				search.append("FROM ").append(getEntityClass().getName());
				search.append(" entity ");
				search.append(" WHERE entity." + getIdEntity() + " = '" + id + "'");
	
				Query query = getEntityManager().createQuery(search.toString());
				entity = (T) query.getSingleResult();

			} catch (NoResultException e) {
				e.printStackTrace();
				entity = null;
			}
		}

		return entity;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getEntityManager().createQuery("from " + getEntityClass().getName())
				.getResultList();
	}
	
	/**
	 * Recupera o nome do campo marcado com a anotacao Id na classe informada
	 * como parametro do dao.
	 * 
	 * @return String que representa o nome do campo Id.
	 * @throws Exception
	 */
	private String getIdEntity() {
		return util.getBeanUtil().getPropertyName(getEntityClass(), Id.class);
	}

	@SuppressWarnings("unchecked")
	public Class<T> getEntityClass() {
		return (Class<T>) getUtil().getBeanUtil().getGenericAttr(this);
	}


	public T saveOrUpdate(T obj) {
		obj = (T) getEntityManager().merge(obj);
		return obj;
	}


	

}
